package com.yyk.yiliao.ui.trade;

import android.graphics.Color;
import android.os.CountDownTimer;
import com.google.android.material.textfield.TextInputEditText;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.bean.Sendsms_Info;
import com.yyk.yiliao.listener.DialogSureCancelListenter;
import com.yyk.yiliao.listener.ToolbarListenter;
import com.yyk.yiliao.util.BtnToEditListenerUtil;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.bean.OrderCodegetInfo;
import com.yyk.yiliao.bean.OrderCodenewInfo;
import com.yyk.yiliao.util.rx.RxUtils;

import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class AddBankcard3Activity extends BaseActivity {


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_phone)
    TextInputEditText etPhone;
    @BindView(R.id.et_sms)
    TextInputEditText etSms;
    @BindView(R.id.tv_sendsms)
    TextView tvSendsms;
    @BindView(R.id.bt_next)
    Button btNext;
    private String merchantFlowId; //订单号

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_bankcard3;
    }

    @Override
    public void initView() {
        initToolbar();
        initButton();
        initTextView();

    }

    private void initButton() {
        BtnToEditListenerUtil.getInstance().setBtn(btNext).setBackgroud(R.color.blue_51, R.color.blue_89)
                .addEditView(etPhone)
                .addEditView(etSms)
                .build();
    }

    private void initTextView() {
        //更改颜色 Android中TextView中部分文字有不同颜色的实现 - 丿灬安之若死 - CSDN博客  https://blog.csdn.net/mp624183768/article/details/78722298
        SpannableString spannableString = new SpannableString("请添加账户本人银行卡");
        spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#148DFF")), spannableString.length() - 7, spannableString.length() - 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvTitle.setText(spannableString);
    }

    private void initToolbar() {
        setBackArrow(new ToolbarListenter() {
            @Override
            public void onClickListenter() {
                DialogUtil.getIntanse().showReturnTips(mActivity, "", "未提交验证码，是否退出", "确定", "取消", new DialogSureCancelListenter() {
                    @Override
                    public void onSureListenter() {
                        finish();
                    }

                    @Override
                    public void onCancelListenter() {

                    }
                }, false);
            }
        });
        setTitle("添加银行卡");
    }

    @Override
    public void initData() {
        initGetIntent();


    }

    private void initGetIntent() {
        if (getBundle() != null) {
            String phone = getBundle().getString("phone");
            merchantFlowId = getBundle().getString("merchantFlowId");
            String maskNumber = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
            etPhone.setText(maskNumber);

            String type = getBundle().getString("type");
            if (type.equals("1")) {
                //自动提示获取验证码
                initSms();
            }
        }
    }
    /**
     * 这个方法 可以改变返回键的状态,禁止返回弹出对话框
     * Android点击返回键back时弹出对话框Dialog - 开发者知识库  http://www.itdaan.com/blog/2014/06/22/6b173aebb9db.html
     *
     * @param keyCode
     * @param event
     * @return
     */

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            DialogUtil.getIntanse().showReturnTips(mActivity, "", "未提交验证码，是否退出", "确定", "取消", new DialogSureCancelListenter() {
                @Override
                public void onSureListenter() {
                    finish();
                }

                @Override
                public void onCancelListenter() {

                }
            }, false);
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    /**
     * 发送验证码
     */

    private int cadeSms; //验证码

    private TimeCount timeCount;


    /**
     * 设置 60秒时间 倒计时
     */
    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            //            mLoginEdit.setBackgroundColor(Color.parseColor("#B6B6D8"));
            tvSendsms.setClickable(false);
            tvSendsms.setText(millisUntilFinished / 1000 + "s后重发");
            tvSendsms.setTextColor(getResources().getColor(R.color.gray_c1));

        }

        @Override
        public void onFinish() {
            tvSendsms.setClickable(true);
            tvSendsms.setText("获取验证码");
            tvSendsms.setTextColor(getResources().getColor(R.color.gray_c1));

        }

    }

    private void initSms() {
        String phone = etPhone.getText().toString().trim();
//        if (phone.length() != 11 || !ValidUtils.getInstance().isValidPhoneNumber(phone)) {
//            ToastUtil.showShort(mActivity, "手机号码格式不正确");
//            return;
//        }
        Map<String, String> map = new TreeMap<>();
        map.put("telphone", phone);


        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postSendsms(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<Sendsms_Info>() {
                    @Override
                    public void onNext(Sendsms_Info info) {
                        Logger.e("发送验证码" + info.toString());
                        if (info.getCode() == 0) {
                            ToastUtil.showShort(mActivity, "短信获取次数过多");
                            return;
                        } else {
                            if (info.getCode() == 1) {
                                //获取到的验证码
                                cadeSms = info.getData();
                                Logger.i("手机验证码" + cadeSms + "");
                            }
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                });
        timeCount = new TimeCount(60000, 1000);
        timeCount.start();
    }

    @OnClick({R.id.tv_sendsms, R.id.bt_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_next:
                sendTieCard();

                break;
            case R.id.tv_sendsms:
                sendSms();
                break;
        }

    }

    private void sendSms() {
        Map<String, String> map = new TreeMap<>();
        map.put("merchantFlowId", merchantFlowId);
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postOrderCodenew(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<OrderCodenewInfo>() {
                    @Override
                    public void onNext(OrderCodenewInfo info) {
                        Logger.e("重发验证码" + info.toString());
                        if (info.getCode() == 1) {
                            ToastUtil.showShort(mActivity, "获取验证码成功");
                        }
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                });
        timeCount = new TimeCount(60000, 1000);
        timeCount.start();
    }

    private void sendTieCard() {
        String sms = etSms.getText().toString().trim();
        if (TextUtils.isEmpty(sms)) {
            ToastUtil.showShort(mActivity, "验证码不能为空");
            return;
        }
        Map<String, String> map = new TreeMap<>();
        map.put("id", Hawk.get("uid") + "");
        map.put("merchantFlowId", merchantFlowId + "");
        map.put("code", sms + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postOrderCodeget(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<OrderCodegetInfo>() {
                    @Override
                    public void onNext(OrderCodegetInfo info) {
                        Logger.e("绑定银行卡第四步" + info.toString());
                        if (info.getCode() == 1) {
//                            ToastUtil.showShort(mActivity, "绑咔成功");
                            startAct(TieCardSuccendActivity.class, true);
                            if (AddBankcard2Activity.intance != null)
                                AddBankcard2Activity.intance.finish();
                            if (AddBankcardActivity.intance != null)
                                AddBankcardActivity.intance.finish();
                        } else if (info.getCode() == 112) {
                            ToastUtil.showShort(mActivity, "请重新获取验证码");
                        } else if (info.getCode() == 113) {
                            ToastUtil.showShort(mActivity, "验证码错误");
                        }

                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                });

    }
}
